package cn.b.sky.admin.service.impl;

import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.admin.dao.LanguagesDao;
import cn.b.sky.admin.model.BatchJobReport;
import cn.b.sky.admin.model.Language;
import cn.b.sky.admin.model.condition.LanguageCondition;
import cn.b.sky.admin.service.LanguagesService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("languagesService")
public class LanguagesServiceImpl implements LanguagesService {

  private static final Logger LOG = LoggerFactory.getLogger(AdminResourceServiceImpl.class);

  @Resource
  private LanguagesDao languagesDao;

  @Override
  public List<Language> selectLanguageByCondition(LanguageCondition condition) {
    if (null==condition) {
      return null;
    }
    return languagesDao.selectLanguageByCondition(condition);
  }

  @Override
  public int selectLanguageCountByCondition(LanguageCondition condition) {
    return languagesDao.selectLanguageCountByCondition(condition);
  }

  @Override
  public void insertLanguage(Language language) {
    languagesDao.insertLanguage(language);
  }

  @Override
  public Language selectLanguageByCode(String code) {
    if (StringUtils.isBlank(code)) {
      return null;
    }
    return languagesDao.selectLanguageByCode(code);
  }

  @Override
  public void updateLanguage(Language language) {
    languagesDao.updateLanguage(language);
  }

  @Override
  public BatchJobReport deleteLanguage(String code) {
    String cause = "";
    Boolean success = true;
    try {
      languagesDao.deleteLanguage(code);
    } catch (Exception e) {
      LOG.error("{}", e);
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        // 外键删除已存在提示
        cause = "数据已被使用,不能删除!";
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport(code, cause, success, "zh");
  }

  @Override
  public Language verifyLanguage(String languageCode) {
    return languagesDao.selectLanguageByCode(languageCode);
  }

}
